default_platform(:android)

platform :android do
  desc "Auto bump versionCode and versionName, build release APK, and upload to Back4App"
  lane :deploy do
    # Auto bump version
    bump_version_code
    
    # Build release APK
    build_release_apk
    
    # Upload to Back4App Dashboard File
    upload_to_back4app
    
    # Generate deployment summary
    generate_deployment_summary
  end
  
  desc "Auto bump versionCode and versionName"
  private_lane :bump_version_code do
    # Get current version from build.gradle.kts
    gradle_path = "../app/build.gradle.kts"
    
    # Read current version
    version_code = android_get_version_code(
      gradle_file: gradle_path,
      flavor: "main"
    )
    
    version_name = android_get_version_name(
      gradle_file: gradle_path,
      flavor: "main"
    )
    
    # Increment version code
    new_version_code = version_code + 1
    
    # Parse version name and increment patch version
    version_parts = version_name.split(".")
    major = version_parts[0].to_i
    minor = version_parts[1].to_i
    patch = version_parts[2].to_i + 1
    new_version_name = "#{major}.#{minor}.#{patch}"
    
    # Update version in build.gradle.kts
    android_set_version_code(
      gradle_file: gradle_path,
      version_code: new_version_code
    )
    
    android_set_version_name(
      gradle_file: gradle_path,
      version_name: new_version_name
    )
    
    # Commit version bump
    git_commit(
      path: [gradle_path],
      message: "Bump version to #{new_version_name} (#{new_version_code})"
    )
    
    # Tag the version
    add_git_tag(
      tag: "v#{new_version_name}"
    )
    
    UI.message "✅ Version bumped to #{new_version_name} (#{new_version_code})"
  end
  
  desc "Build release APK"
  private_lane :build_release_apk do
    gradle(
      task: "clean assembleRelease",
      properties: {
        "android.injected.signing.store.file" => ENV["KEYSTORE_PATH"],
        "android.injected.signing.store.password" => ENV["KEYSTORE_PASSWORD"],
        "android.injected.signing.key.alias" => ENV["KEY_ALIAS"],
        "android.injected.signing.key.password" => ENV["KEY_PASSWORD"]
      }
    )
    
    UI.message "✅ Release APK built successfully"
  end
  
  desc "Upload APK to Back4App Dashboard File"
  private_lane :upload_to_back4app do
    apk_path = lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH]
    
    # Get current version info
    version_name = android_get_version_name
    version_code = android_get_version_code
    
    # Create upload metadata
    upload_data = {
      "version" => version_name,
      "versionCode" => version_code,
      "buildDate" => Time.now.strftime("%Y-%m-%d %H:%M:%S"),
      "gitCommit" => last_git_commit[:commit_hash],
      "gitBranch" => git_branch,
      "buildType" => "release"
    }.to_json
    
    # Upload to Back4App Files
    back4app_upload(
      file_path: apk_path,
      file_name: "GuessWho-v#{version_name}-#{version_code}.apk",
      metadata: upload_data
    )
    
    # Generate QR code for download
    generate_qr_code(
      version: version_name,
      apk_path: apk_path
    )
    
    UI.message "✅ APK uploaded to Back4App Dashboard"
  end
  
  desc "Upload file to Back4App"
  private_lane :back4app_upload do |options|
    require 'net/http'
    require 'uri'
    require 'json'
    
    file_path = options[:file_path]
    file_name = options[:file_name]
    metadata = options[:metadata]
    
    # Back4App API endpoint
    uri = URI.parse("https://parseapi.back4app.com/files/#{file_name}")
    
    # Prepare file upload
    boundary = "----WebKitFormBoundary#{SecureRandom.hex(16)}"
    post_body = []
    
    # Add metadata
    post_body << "--#{boundary}\r\n"
    post_body << "Content-Disposition: form-data; name=\"metadata\"\r\n"
    post_body << "Content-Type: application/json\r\n\r\n"
    post_body << "#{metadata}\r\n"
    
    # Add file
    post_body << "--#{boundary}\r\n"
    post_body << "Content-Disposition: form-data; name=\"file\"; filename=\"#{file_name}\"\r\n"
    post_body << "Content-Type: application/vnd.android.package-archive\r\n\r\n"
    post_body << File.binread(file_path)
    post_body << "\r\n"
    
    post_body << "--#{boundary}--\r\n"
    
    # Send HTTP request
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    
    request = Net::HTTP::Post.new(uri.request_uri)
    request.body = post_body.join
    request["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
    request["X-Parse-Application-Id"] = ENV["BACK4APP_APP_ID"]
    request["X-Parse-REST-API-Key"] = ENV["BACK4APP_REST_KEY"]
    
    response = http.request(request)
    
    if response.code == "201"
      json_response = JSON.parse(response.body)
      UI.success "File uploaded successfully: #{json_response['url']}"
      Actions.lane_context[SharedValues::BACK4APP_FILE_URL] = json_response['url']
    else
      UI.error "Failed to upload file: #{response.body}"
      raise "Back4App upload failed"
    end
  end
  
  desc "Generate QR code for APK download"
  private_lane :generate_qr_code do |options|
    version = options[:version]
    apk_path = options[:apk_path]
    
    # Create QR code data (Back4App file URL would be here)
    qr_data = lane_context[SharedValues::BACK4APP_FILE_URL] || "https://back4app.com/download/guesswho/v#{version}"
    
    # Generate QR code image
    require 'rqrcode'
    
    qrcode = RQRCode::QRCode.new(qr_data)
    png = qrcode.as_png(
      size: 300,
      border_modules: 4,
      module_px_size: 6,
      fill: 'chunky',
      color: '000'
    )
    
    qr_path = "../fastlane/qrcodes/GuessWho-v#{version}-QR.png"
    FileUtils.mkdir_p(File.dirname(qr_path))
    File.binwrite(qr_path, png.to_s)
    
    UI.message "✅ QR code generated: #{qr_path}"
  end
  
  desc "Generate deployment summary"
  private_lane :generate_deployment_summary do
    version_name = android_get_version_name
    version_code = android_get_version_code
    apk_url = lane_context[SharedValues::BACK4APP_FILE_URL]
    
    summary = {
      "version" => version_name,
      "versionCode" => version_code,
      "deployed_at" => Time.now.strftime("%Y-%m-%d %H:%M:%S"),
      "apk_url" => apk_url,
      "git_commit" => last_git_commit[:commit_hash],
      "git_branch" => git_branch
    }
    
    # Save deployment summary
    File.write("../fastlane/deployment_summary.json", JSON.pretty_generate(summary))
    
    UI.message "📋 Deployment Summary:"
    UI.message "   Version: #{version_name} (#{version_code})"
    UI.message "   APK URL: #{apk_url}" if apk_url
    UI.message "   Git Commit: #{last_git_commit[:commit_hash]}"
    UI.message "   Deployed at: #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}"
  end
  
  desc "Setup environment for deployment"
  lane :setup do
    # Create .env file template
    env_template = <<-TEMPLATE
# Back4App Configuration
BACK4APP_APP_ID=your_back4app_app_id_here
BACK4APP_REST_KEY=your_back4app_rest_key_here

# Keystore Configuration
KEYSTORE_PATH=/path/to/your/keystore.jks
KEYSTORE_PASSWORD=your_keystore_password
KEY_ALIAS=your_key_alias
KEY_PASSWORD=your_key_password

# Bugly Configuration
BUGLY_APP_ID=your_bugly_app_id_here
    TEMPLATE
    
    File.write(".env.template", env_template)
    UI.message "📝 Created .env.template file"
    
    # Create qrcodes directory
    FileUtils.mkdir_p("qrcodes")
    UI.message "📁 Created qrcodes directory"
    
    UI.message "✅ Setup complete! Please:"
    UI.message "   1. Copy .env.template to .env and fill in your credentials"
    UI.message "   2. Install required gems: bundle install"
    UI.message "   3. Run: fastlane deploy"
  end
  
  desc "Test deployment (dry run)"
  lane :test_deploy do
    UI.message "🧪 Testing deployment process..."
    
    # Test version bump (dry run)
    current_version = android_get_version_name
    UI.message "Current version: #{current_version}"
    
    # Test gradle clean
    gradle(task: "clean")
    
    UI.message "✅ Deployment test completed successfully"
  end
end